package com.example.day2.busi.home;

import android.content.Intent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.day2.R;
import com.example.day2.adapter.CommentAdapter;
import com.example.day2.adapter.VideoAdapter;

import com.example.day2.databinding.FragmentRecommendBinding;
import com.example.day2.db.MyDataBase;
import com.example.day2.db.StoreVideoDap;
import com.example.day2.entity.CheckLogin;
import com.example.day2.entity.CommentFSParam;
import com.example.day2.entity.CommentFSResult;
import com.example.day2.entity.CommentResult;
import com.example.day2.entity.LiveResult;
import com.example.day2.entity.NoLiveReuslt;
import com.example.day2.entity.NormalResult;
import com.example.day2.entity.VideoResult;
import com.example.day2.live.LiveActivity;
import com.example.day2.mvvm.base.BaseFragment;
import com.example.day2.mvvm.base.GuanZhuParam;
import com.example.day2.mvvm.utils.DBUtils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

public class RecommendFragment extends BaseFragment<FragmentRecommendBinding,VideoViewModel> {
    List<CommentResult.DataBean> list = new ArrayList<>();
    private int page = 1;
    private int size = 5;
    private VideoAdapter videoAdapter = new VideoAdapter();

    private CommentAdapter commentAdapter = new CommentAdapter(R.layout.item_comment,list);

    int position = 0;


    @Override
    public void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        binding.rv.setLayoutManager(linearLayoutManager);
        binding.rv.setAdapter(videoAdapter);

        viewModel.getVideo(page,size);

        binding.tt.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getVideo(++page,5);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                videoAdapter.getData().clear();
                page = 1;
                viewModel.getVideo(page,size);
            }
        });
        //滑动一整条
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(binding.rv);
        //自动播放
        binding.rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                position = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
                StandardGSYVideoPlayer viewByPosition = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position, R.id.play);
                if (viewByPosition!= null){
                    viewByPosition.startPlayLogic();
                }
            }
        });
        //设置条目中可点击的id
        videoAdapter.addChildClickViewIds(R.id.add_iv,R.id.dz_iv,R.id.pl_iv,R.id.share_iv,R.id.shouc_iv,R.id.pl_iv,R.id.sc,R.id.rv,R.id.et,R.id.fs_iv,R.id.fuil,R.id.live);

        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                VideoResult.DataBean dataBean = (VideoResult.DataBean)videoAdapter.getData().get(position);
                switch (view.getId()){
                    case R.id.add_iv:
                        guanzhu(dataBean);
                        break;
                    case R.id.dz_iv:
                        dianzan(dataBean);
                        break;
                    case R.id.share_iv:
                        store(dataBean);
                        break;
                    case R.id.shouc_iv:
                        fengxiang(dataBean);
                        break;
                    case R.id.pl_iv:

                        OpenComment(dataBean);
                        break;
                    case R.id.sc:
                        CloseComment(dataBean);
                        break;
                    case R.id.fs_iv:

                        SendComment(dataBean);
                        break;
                    case R.id.fuil:

                        fullScreen();
                        break;
                    case R.id.live:

                        Live(dataBean);
                        break;
                }
            }
        });


    }

    private void Live(VideoResult.DataBean dataBean) {
        Intent intent = new Intent(getContext(), LiveActivity.class);
        intent.putExtra("video",dataBean);
        startActivity(intent);
    }

    private void fullScreen() {
        StandardGSYVideoPlayer viewByPosition = (StandardGSYVideoPlayer) videoAdapter.getViewByPosition(position, R.id.play);
        viewByPosition.startWindowFullscreen(getContext(),false,false);
    }

    private void SendComment(VideoResult.DataBean dataBean) {
        EditText editText = (EditText) videoAdapter.getViewByPosition(position, R.id.et);
        String s = editText.getText().toString();
        CommentFSParam commentFSParam = new CommentFSParam();
        commentFSParam.setMsg(s);
        commentFSParam.setVideoId(dataBean.getId());
        viewModel.getCommentFS(commentFSParam);
        editText.setText(null);
    }

    //打开评论界面
    private void OpenComment(VideoResult.DataBean dataBean) {
        binding.rv.setInterept(false);
        //显示评论界面
        View view = videoAdapter.getViewByPosition(position, R.id.ll);
        view.setVisibility(View.VISIBLE);

        RecyclerView rv2 = (RecyclerView) videoAdapter.getViewByPosition(position,R.id.rv);
        rv2.setAdapter(commentAdapter);
        rv2.setLayoutManager(new LinearLayoutManager(getContext()));
        viewModel.getCommentHQ(dataBean.getId());



        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.item_pl_anim);
        animation.setInterpolator(new BounceInterpolator());
        view.startAnimation(animation);
    }
    //关闭评论界面
    private void CloseComment(VideoResult.DataBean dataBean) {
        binding.rv.setInterept(true);
        //显示评论界面
        View view = videoAdapter.getViewByPosition(position, R.id.ll);
        view.setVisibility(View.GONE);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.item_pl_anim_tui);
        view.startAnimation(animation);
    }

    private void fengxiang(VideoResult.DataBean dataBean) {
        //缩略图
        UMImage umImage = new UMImage(getContext(), dataBean.getVideomainimg());
        umImage.compressStyle = UMImage.CompressStyle.SCALE;//压缩图片大小
        UMWeb web =new UMWeb(dataBean.getVideopath());
        web.setTitle(dataBean.getCaption());//标题
        web.setThumb(umImage);//缩略图
        web.setDescription("my description");//描述
        new ShareAction(getActivity())
                .withMedia(web)
                .open();
    }

    @CheckLogin
    private void store(VideoResult.DataBean dataBean) {

        ImageView iv= (ImageView) videoAdapter.getViewByPosition(position,R.id.share_iv);
        StoreVideoDap dao=DBUtils.getInstance().getStoreVideoDap();
        if(dao.getById(dataBean.getId())!=null){
            dao.delete(dataBean);
            iv.setImageResource(R.drawable.ic_shoucang);
        }else{
            DBUtils.getInstance().getStoreVideoDap().add(dataBean);
            iv.setImageResource(R.drawable.ic_shoucangyellow);
        }
    }
   private long lastTime;
@CheckLogin
    private void dianzan(VideoResult.DataBean dataBean) {
    //通过点击时间间隔，判断是否连点
    long now = System.currentTimeMillis();
    if (now - lastTime > 2000){
        TextView viewByPosition = (TextView) videoAdapter.getViewByPosition(position, R.id.dz);
        if (dataBean.getDianzan() == 1){
            viewModel.getNOlive(dataBean.getId());
            viewByPosition.setText(dataBean.getLike_count()+"");
        }else{
            viewModel.getLives(dataBean.getId());
            viewByPosition.setText(dataBean.getLike_count()+"");
        }
    }else{
        ToastUtils.showLong("不可连续点击");

    }
    lastTime = now;
    }
@CheckLogin
    private void guanzhu(VideoResult.DataBean dataBean) {
        GuanZhuParam guanZhuParam = new GuanZhuParam();
        guanZhuParam.setAuthname(dataBean.getAuthname());
        viewModel.getGuanzhu(guanZhuParam);

    }

    @Override
    public void initData() {
        //创建数据库
        MyDataBase myDataBase = Room.databaseBuilder(getContext(), MyDataBase.class, "mydb.db").allowMainThreadQueries().build();
        myDataBase.getStoreVideoDao().getAll();


        viewModel.success.observe(RecommendFragment.this, new Observer<VideoResult>() {
            @Override
            public void onChanged(VideoResult videoResult) {
                if (videoResult.getCode() == 200){
                    binding.ivIcon.setVisibility(View.GONE);
                    videoAdapter.getData().addAll(videoResult.getData());
                    videoAdapter.notifyDataSetChanged();
                    binding.tt.finishLoadMore();
                    binding.tt.finishRefresh();


                }

            }
        });

        viewModel.fail.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                ToastUtils.showLong("网络异常");
                binding.ivIcon.setVisibility(View.VISIBLE);
            }
        });
        viewModel.GuanSuccess.observe(this, new Observer<NormalResult>() {
            @Override
            public void onChanged(NormalResult normalResult) {
                if (normalResult.getCode() == 200){
                    // videoAdapter.getViewByPosition(position,R.id.add_iv).setVisibility(View.INVISIBLE);
                    ImageView iv = (ImageView) videoAdapter.getViewByPosition(position,R.id.add_iv);
                  //  内存中的数据修改为关注
                    videoAdapter.getData().get(position).setGuanzhu(1);
                    videoAdapter.notifyDataSetChanged();
                    iv.setImageResource(R.drawable.ic_duigou);
                    Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.ani_aloha);
                    iv.startAnimation(animation);
                }
            }
        });
        //点赞完的回调
        viewModel.successLive.observe(this, new Observer<LiveResult>() {
            @Override
            public void onChanged(LiveResult liveResult) {
                VideoResult.DataBean dataBean = videoAdapter.getData().get(position);

                ImageView imageView = (ImageView) videoAdapter.getViewByPosition(position, R.id.dz_iv);
                imageView.setImageResource(R.drawable.ic_xihuanred);
                RotateAnimation rotateAnimation = new RotateAnimation(-20, 20,
                        Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1);
                rotateAnimation.setRepeatCount(2);
                rotateAnimation.setDuration(10);
                imageView.startAnimation(rotateAnimation);


                rotateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        dataBean.setDianzan(1);
                        videoAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
        });
        viewModel.successNOLive.observe(this, new Observer<NoLiveReuslt>() {
            @Override
            public void onChanged(NoLiveReuslt noLiveReuslt) {
                VideoResult.DataBean dataBean = videoAdapter.getData().get(position);

                ImageView imageView = (ImageView) videoAdapter.getViewByPosition(position, R.id.dz_iv);
                imageView.setImageResource(R.drawable.ic_xihuan);

                dataBean.setDianzan(0);
                videoAdapter.notifyDataSetChanged();
            }

        });
        viewModel.successCommentFS.observe(this, new Observer<CommentFSResult>() {
            @Override
            public void onChanged(CommentFSResult commentFSResult) {
                viewModel.getCommentHQ(videoAdapter.getData().get(position).getId());
            }
        });
        viewModel.successCommentHQ.observe(this, new Observer<CommentResult>() {
            @Override
            public void onChanged(CommentResult commentResult) {
                commentAdapter.getData().clear();
                commentAdapter.getData().addAll(commentResult.getData());
                commentAdapter.notifyDataSetChanged();

            }
        });

        binding.ivIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.ivIcon.setVisibility(View.GONE);
                viewModel.getVideo(2,15);
            }
        });
    }
//页面生命周期，与播放的生命周期一致
    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }


    @Override
    public Class<VideoViewModel> getVIewModel() {
        return VideoViewModel.class;
    }

    @Override
    public int bindLayoutId() {
        return R.layout.fragment_recommend;
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
    }

}
